package com.tiger.userClient.http.news;

import com.tiger.cache.RedisService;
import com.tiger.userClient.http.news.type.ApiConfig;
import org.apache.axis.AxisFault;
import org.springframework.stereotype.Service;

import javax.xml.rpc.ServiceException;

import static java.util.concurrent.TimeUnit.SECONDS;

@Service
public class NewsService {

    private final ApiConfig apiConfig;
    private final RedisService redisService;

    public NewsService(ApiConfig apiConfig, RedisService redisService) {
        this.apiConfig = apiConfig;
        this.redisService = redisService;
    }


    public String queryNews(String start, String end) throws ServiceException, AxisFault {
        String key = "news";
        String res = redisService.template.opsForValue().get(key);
        if (res != null && !res.isEmpty()) {
            boolean lock = Boolean.TRUE.equals(redisService.template.opsForValue().setIfAbsent("get:news", "1", 10, SECONDS));
            if(!lock) return res;
        }

        //创建 Service实例
        org.apache.axis.client.Service service = new org.apache.axis.client.Service();
        org.apache.axis.client.Call call;

        call = (org.apache.axis.client.Call) service.createCall();
        call.setTargetEndpointAddress(apiConfig.getUrl());

        System.out.println("查询新闻");
        System.out.println(apiConfig.getUrl());
        System.out.println(apiConfig.getOwner());

        res = (String) call.invoke("getlistByTime", new Object[]{apiConfig.getOwner(), start, end});
        redisService.template.opsForValue().set(key, res);

        return res;
    }

    public String queryNewsByContentId(String contentid, int start, int count) throws ServiceException, AxisFault {
        //创建 Service实例
        org.apache.axis.client.Service service = new org.apache.axis.client.Service();
        org.apache.axis.client.Call call;

        call = (org.apache.axis.client.Call) service.createCall();
        call.setTargetEndpointAddress(apiConfig.getUrl());

        System.out.println("查询新闻queryNewsByContentId");
        System.out.println(apiConfig.getUrl());
        System.out.println(apiConfig.getOwner());


        return (String) call.invoke("getListByContentId", new Object[]{apiConfig.getOwner(), contentid, start, count});
    }

    public String detail(int wbnewsid) throws ServiceException, AxisFault {
        //创建 Service实例
        org.apache.axis.client.Service service = new org.apache.axis.client.Service();
        org.apache.axis.client.Call call;

        call = (org.apache.axis.client.Call) service.createCall();
        call.setTargetEndpointAddress(apiConfig.getUrl());

        return (String) call.invoke("getWbnewsById", new Object[]{wbnewsid, apiConfig.getOwner()});
    }
}
